package org.swim.session;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.jboss.ejb3.annotation.RemoteBinding;
import org.swim.entity.Ability;


@Stateless
@RemoteBinding(jndiBinding="AbilityManagerRemote")
public class AbilityManager implements AbilityManagerRemote {

	/**
	 * Manager degli entity beans. Permette di interagire direttamente col database inserendo e ricercando dati
	 */
	@PersistenceContext(unitName="swim") private EntityManager manager;
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public int defineNewAbility(String name) {
		
		Ability toDefine=new Ability();
		toDefine.setNome(name);
		manager.persist(toDefine);
		
		return toDefine.getIdAbilita();
		
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public List<Ability> getAllDefinedAbility() {
		
		List<Ability> result = new ArrayList<Ability>();
		
		try 
		{
			Query q = manager.createQuery("SELECT OBJECT(ab) FROM Ability AS ab");
			
			@SuppressWarnings("unchecked")
			Collection<Ability> coll = (Collection<Ability>) q.getResultList();
			Iterator<Ability> itar = coll.iterator();
			
			while (itar.hasNext())
			{	
				Ability ab = itar.next();
				result.add(ab);
			}
		} 
		catch (EntityNotFoundException exc){} 
		
		return result;		
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void deleteAbility(int abilityID) {
		
		Ability ab = new Ability();
		ab = manager.find(Ability.class, abilityID);
		if(ab != null)
			manager.remove(ab);	
		
	}
	
	

}
